<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Information</title>

    <style>
        html {
            margin: 0;
            padding: 0;
            height: 100%;
            background: url('img/background.png') no-repeat center center;
            background-size: 95%;
            background-color: #000;
            background-attachment: fixed;
            image-rendering: pixelated;
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100%;
        }

        #top {
            height: 50px;
            width: 100%;
            background-color: #000;
            display: flex;
            align-items: center; /* 垂直居中 */
            justify-content: space-between; /* 左右两端对齐 */
            padding: 0 10px;
            box-sizing: border-box;
        }

        #loge {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        #loge img {
            height: 40px;
            width: 40px;
            image-rendering: pixelated;
        }

        #loge p {
            color: #d1d1d1;
            font-size: 20px;
            margin: 0;
        }

        #login {
            height: 50px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        #login p {
            color: #d1d1d1;
            font-size: 16px;
            margin: 0;
            user-select: none;
        }

        #content {
            margin: 0 auto;
            width: 75%;
            min-height: calc(100vh - 50px);
            background-color: #2c2925;
        }

        /* 底部占位符 */
        #bottomSpacer {
            height: 50px;
        }

    </style>
</head>
<body>
    <div id="top">
        <div id="loge">
            <img src="img/site_avatar_isaac_l.webp" alt="Isaac Wiki">
            <p>以撒的结合Wiki</p>
        </div>
        <div id="login">
            <!-- 预留登录/注册区域 -->
        </div>
    </div>
    <div id="content">
    </div>
</body>

<script src="js/jQuery-3.7.1.min.js"></script>
<script>
    $(document).ready(function () {
        const userId = localStorage.getItem("id");

        if (!userId) {
            alert("未登录，无法查看用户信息！");
            window.location.href = "login.html";
            return;
        }

        // 发起请求获取用户信息
        $.ajax({
            url: `http://localhost:8080/getUser?id=${userId}`,
            type: 'GET',
            success: function (res) {
                if (res.code === 1) {
                    const userData = res.data;
                    const imgUrl = userData.imgUrl || "img/default_avatar.png";
                    const name = userData.user.name || "未知用户";

                    // 拼接内容
                    const html = `
<div id="userInfoContainer" style="padding-top:50px; text-align:center;">
    <img src="${imgUrl}" alt="头像" style="height:120px; width:120px; border-radius:50%; object-fit:cover; image-rendering:pixelated;">
    <h1 style="color:#d1d1d1; margin:20px 0 30px 0;">${name}</h1>
    <button id="editBtn" style="padding:10px 30px; font-size:18px; background-color:#202e63; color:#fff; border:none; border-radius:8px; cursor:pointer;">修改信息</button>

    <div id="editArea" style="margin-top:30px; display:none; color:#d1d1d1; text-align:left; max-width:400px; margin-left:auto; margin-right:auto;">
        <div id="basicInfoEdit" style="margin-bottom:30px;">
            <h3 style="color:#d1d1d1;">用户基本信息修改</h3>
            <div style="margin-bottom:10px;">
                <label>新头像: </label>
                <input type="file" id="newAvatar" accept="image/*" style="width:100%; background-color:#444; color:#fff; border:1px solid #888; border-radius:5px; padding:8px;">
            </div>
            <div style="margin-bottom:10px;">
                <label>新名称: </label>
                <input type="text" id="newName" placeholder="请输入新名称" style="width:100%; background-color:#444; color:#fff; border:1px solid #888; border-radius:5px; padding:8px;">
            </div>
            <button id="confirmBasic" style="padding:8px 20px; background-color:#3040a0; border:none; border-radius:6px; color:#fff; cursor:pointer; margin-top:10px;">确认修改</button>
        </div>

        <div id="passwordEdit">
            <h3 style="color:#d1d1d1;">用户密码修改</h3>
            <div style="margin-bottom:10px;">
                <label>旧密码: </label>
                <input type="password" id="oldPassword" placeholder="请输入旧密码" style="width:100%; background-color:#444; color:#fff; border:1px solid #888; border-radius:5px; padding:8px;">
            </div>
            <div style="margin-bottom:10px;">
                <label>新密码: </label>
                <input type="password" id="newPassword" placeholder="请输入新密码" style="width:100%; background-color:#444; color:#fff; border:1px solid #888; border-radius:5px; padding:8px;">
            </div>
            <button id="confirmPassword" style="padding:8px 20px; background-color:#3040a0; border:none; border-radius:6px; color:#fff; cursor:pointer; margin-top:10px;">确认修改</button>
        </div>
    </div>
</div>
    <div id="bottomSpacer"></div>
`;


                    $("#content").prepend(html);

                    // 绑定修改信息按钮点击事件
                    $("#editBtn").click(function () {
                        const $btn = $(this);
                        const $editArea = $("#editArea");

                        if ($editArea.is(":visible")) {
                            // 如果内容是显示的 → 隐藏它 & 改按钮文字
                            $editArea.slideUp();
                            $btn.text("修改信息");
                        } else {
                            // 如果内容是隐藏的 → 显示它 & 改按钮文字
                            $editArea.slideDown();
                            $btn.text("取消");
                        }
                    });

                    // 基本信息修改
                    $("#confirmBasic").click(function () {
                        const userId = localStorage.getItem("id");
                        const fileInput = $("#newAvatar")[0].files[0];
                        const newName = $("#newName").val().trim();

                        // 检查：头像和名称不能同时为空
                        if (!fileInput && !newName) {
                            alert("头像和名称不能同时为空！");
                            return;
                        }

                        // 上传头像，准备 formData
                        let formData = new FormData();
                        if (fileInput) {
                            formData.append("file", fileInput);
                        }

                        // 先上传图片（如果有）
                        $.ajax({
                            url: "http://localhost:8080/updateImage",
                            type: "POST",
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function (res) {
                                if (res.code !== 1) {
                                    alert("头像上传失败！");
                                    return;
                                }

                                const imgUrl = res.data;  // 可能是 "no update" 或具体 URL

                                // 然后提交信息修改
                                $.ajax({
                                    url: "http://localhost:8080/updateUserInfo",
                                    type: "POST",
                                    data: {
                                        id: userId,
                                        name: newName || null,
                                        imgUrl: imgUrl
                                    },
                                    success: function (res2) {
                                        if (res2.code !== 1) {
                                            alert("信息修改失败！");
                                            return;
                                        }

                                        // 成功 → 更新 localStorage
                                        const updatedUser = res2.data;

                                        if (newName) {
                                            localStorage.setItem("name", updatedUser.name);
                                        }
                                        if (imgUrl !== "no update") {
                                            localStorage.setItem("imgUrl", imgUrl);
                                        }

                                        alert("修改成功！");
                                        location.reload();
                                    },
                                    error: function (err2) {
                                        alert("信息修改请求失败！");
                                        console.error(err2);
                                    }
                                });
                            },
                            error: function (err) {
                                alert("头像上传请求失败！");
                                console.error(err);
                            }
                        });
                    });
                    $("#confirmPassword").click(function () {
                        const userId = localStorage.getItem("id");
                        const oldPassword = $("#oldPassword").val().trim();
                        const newPassword = $("#newPassword").val().trim();

                        // 必须两个都不为空
                        if (!oldPassword || !newPassword) {
                            alert("旧密码和新密码都不能为空！");
                            return;
                        }

                        // 发起请求
                        $.ajax({
                            url: "http://localhost:8080/updateUserPasswordById",
                            type: "POST",
                            data: {
                                id: userId,
                                oldPassword: oldPassword,
                                newPassword: newPassword
                            },
                            success: function (res) {
                                if (res.code === 1) {
                                    alert("密码修改成功！");
                                    // 清空输入框
                                    $("#oldPassword").val("");
                                    $("#newPassword").val("");
                                } else {
                                    alert(res.msg || "密码修改失败！");
                                }
                            },
                            error: function (err) {
                                alert("请求失败！");
                                console.error(err);
                            }
                        });
                    });

                } else {
                    alert(res.msg || "获取用户信息失败！");
                }
            },
            error: function (err) {
                alert("请求失败！");
                console.error(err);
            }
        });
    })
</script>
</html>